package com.example.fragment;

import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentOnAttachListener;

import com.example.fragment.databinding.ActivityMainBinding;

import java.util.Locale;

// 必须实现Fragment的接口，
public class MainActivity extends AppCompatActivity
        implements ContentFragment.OnItemSelectedListener {
    private static final String MESSAGE_KEY = "msg_key";
    private FragmentManager manager;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        final TitleFragment titleFragment = TitleFragment.newInstance();
        replaceFragment(R.id.fragment_title, titleFragment);
        // 静态工程方法传值
        replaceFragment(R.id.fragment_content, ContentFragment.newInstance(getResources().getString(R.string.content_fragment)));

        // 调用fragment的特定方法传递数据
        // titleFragment.receiveMsg("Activity传递给Fragment的信息");
        // 调用setArgument()传递bundle
        final Bundle bundle = new Bundle();
        bundle.putString(MESSAGE_KEY, "Activity传递给Fragment的信息");
        titleFragment.setArguments(bundle);

        // 设置Fragment的监听器
        manager.addFragmentOnAttachListener(new FragmentOnAttachListener() {
            @Override
            public void onAttachFragment(@NonNull FragmentManager fragmentManager,
                                         @NonNull Fragment fragment) {
                if (fragment instanceof ContentFragment) {
                    ContentFragment contentFragment = (ContentFragment) fragment;
                    contentFragment.setOnItemSelectedListener(MainActivity.this);
                }
            }
        });
    }

    private void replaceFragment(int containerId, Fragment fragment) {
        // 1. 调用getSupportFragmentManager()获取兼容库的FragmentManager
        manager = getSupportFragmentManager();
        manager.beginTransaction() // 2. 开启一个事务
                .replace(containerId, fragment) // 3. 向容器添加或替换fragment
                .addToBackStack(null) // 4. 将fragment加入回退栈，但后续不再访问（可选）
                .commit(); // 5. 提交事务
    }

    // 实现接口方法，供Fragment回调
    @Override
    public void onContentSelected(int position) {
        Toast.makeText(this, String.format(Locale.CHINA, "点击了第%d个", position),
                Toast.LENGTH_SHORT).show();
    }
}